/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {boolean}
 * @description f612 虽说是递归套递归，但易懂，性能有点差了......刚开始题理解错了，没看到“每个节点”，再然后返回那里弄错了 ，半天没找到问题，再然后是变量名写错了，啊淦，最后发现了............
 */
var isBalanced = function(root) {
    if(!root) return true;
    let flag = true
    let res = 0  //子树深度
	let getDeep = function(root,d){  //当前树的深度(前序遍历)
        if(root == null){ 
            return;
        }else{
            d++;
        }
        if( !root.left && !root.right){ //叶子节点
            res = Math.max(res,d)
        }
        getDeep(root.left,d)
        getDeep(root.right,d)
    }
    let balance = function(root){
        res = 0
        getDeep(root.left,0)
        left = res
        res = 0
        getDeep(root.right,0)
        right = res
        if((Math.abs(left-right))>1) {
            flag = false
            return;
        }
        if(root&&root.left)  balance(root.left)
        if(root&&root.right) balance(root.right)
    }
    balance(root)
    return flag
};